package com.shop.mall.utils;

import com.shop.mall.utils.PropertiesUtil;

import java.sql.*;

/**
 * @author admin
 * @version 1.0
 * @date 2019/4/23
 */
public class MysqlDb {
    private final static String DRIVER_CLASS = PropertiesUtil.getProperties("jdbc.driverClassName");
    private final static String URL = PropertiesUtil.getProperties("jdbc.url");
    private final static String NAME = PropertiesUtil.getProperties("jdbc.username");
    private final static String PASSWORD = PropertiesUtil.getProperties("jdbc.password");


    /**
     * 获取数据库连接
     */
    public static Connection getConnection() throws Exception {
        Connection conn = null;
        try {
            Class.forName(DRIVER_CLASS);
            conn = DriverManager.getConnection(URL, NAME, PASSWORD);
            System.out.println(conn == null ? "Mysql连接失败" : "Mysql连接成功");
        } catch (Exception ex) {
            ex.printStackTrace();
            throw new Exception("Mysql连接失败：" + ex.getMessage());
        }
        return conn;
    }

    /**
     * 关闭连接 释放内存
     */
    public static void closeAll(ResultSet rs, PreparedStatement ps, Connection conn)
            throws Exception {
        try {
            if (rs != null) {
                rs.close();
            }
            if (ps != null) {
                ps.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception ex) {
            throw new Exception("出错了" + ex.getMessage());
        }
    }

    /**
     * 关闭连接 释放内存
     */
    public static void closeAll(ResultSet rs, CallableStatement cs, Connection conn)
            throws Exception {
        try {
            if (rs != null) {
                rs.close();
            }
            if (cs != null) {
                cs.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception ex) {
            throw new Exception("出错了" + ex.getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println(getConnection());
    }
}
